<?php

/**
 * MCache
 * @todo : (1)zip (2)value是数组对象时的处理
 */

class Tool_Memcache
{
    static $memcache = NULL;

	function __init()
	{
		if (empty(self::$memcache))
		{
			self::$memcache = memcache_connect('127.0.0.1', 11333);
		}
	}

    function set($key, $value, $expire = 0)
    {
    	self::__init();

     	return memcache_set(self::$memcache, $key, $value, 0, $expire);
    }

    function get($key)
    {
    	self::__init();

		return memcache_get(self::$memcache, $key);
    }

    function add($key, $value, $expire = 0)
    {
        $para = array(
            'key' => strval($key),
            'value' => strval($value),
            );
        if ($expire > 0)
        {
            $para['expire'] = $expire;
        }
        $ret = $this->proxy->invoke('add', $para);
        return $ret['ok'];
    }

    function replace($key, $value, $expire = 0)
    {
        $para = array(
            'key' => strval($key),
            'value' => strval($value),
            );
        if ($expire > 0)
        {
            $para['expire'] = $expire;
        }
        $ret = $this->proxy->invoke('replace', $para);
        return $ret['ok'];
    }

    function getMulti($keys)
    {
        if (empty($keys))
        {
            return array();
        }

        $keys = array_map("strval", array_unique($keys));
        $len = count($keys);
        $tmpRet = array();
        for ($i = 0; $i < $len; $i+=500)
        {
            $subkey = array_slice($keys, $i, 500);
            $pars = array("keys" => $subkey);
            $ret = $this->proxy->invoke("getMulti", $pars);
            $tmpRet = array_merge($tmpRet, $ret['values']);
        }

        $ret = array();
        foreach ($tmpRet as $k => $v)
        {
            $v = strval($v);
            if (strlen($v))
            {
                $ret[$k] = $v;
            }
        }
        return $ret;
    }

    function delete($key)
    {
        $pars = array(
            "key" => $key,
        );
        $ret = $this->proxy->invoke("delete", $pars);
        return $ret['ok'];
    }

    function increment($key , $value)
    {
        $para = array(
            'key' => $key,
            'value' => $value,
            );
        $ret = $this->proxy->invoke('increment', $para);
        if ($ret["ok"])
        {
            return $ret["value"];
        }
        else
        {
            return false;
        }
    }

    function decrement($key , $value)
    {
        $para = array(
            'key' => $key,
            'value' => $value,
            );
        $ret = $this->proxy->invoke('decrement', $para);
        if ($ret["ok"])
        {
            return $ret["value"];
        }
        else
        {
            return false;
        }
    }
}
?>